import json
import os
import tkinter as tk
from tkinter import simpledialog
import zhipuai

def save_api_key():
    root = tk.Tk()
    root.withdraw()
    api_key = simpledialog.askstring("Input", "Please enter your Zhipuai API key:")
    
    if api_key:
        config = {"api_key": api_key}
        with open("config.json", "w") as f:
            json.dump(config, f)
        print("API key saved successfully.")
    else:
        print("No API key provided.")

def load_api_key():
    try:
        with open("config.json", "r") as f:
            config = json.load(f)
        return config.get("api_key")
    except FileNotFoundError:
        return None

def translate_json(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    translated_data = {}
    for key, value in data.items():
        response = zhipuai.model_api.invoke(
            model="glm-4-flash",
            prompt=[
                {"role": "system", "content": "帮我翻译json文件值，不要传回我别的信息。"},
                {"role": "user", "content": f"请翻译以下内容：{value}"}
            ]
        )
        translated_value = response['data']['choices'][0]['content']
        translated_data[key] = translated_value
    
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(translated_data, f, ensure_ascii=False, indent=2)

def main():
    api_key = load_api_key()
    if not api_key:
        save_api_key()
        api_key = load_api_key()
    
    if not api_key:
        print("No API key found. Exiting.")
        return

    zhipuai.api_key = api_key

    input_folder = "input"
    output_folder = "output"
    
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    for filename in os.listdir(input_folder):
        if filename.endswith(".json"):
            input_file = os.path.join(input_folder, filename)
            output_file = os.path.join(output_folder, filename)
            translate_json(input_file, output_file)
            print(f"Translated {filename}")

if __name__ == "__main__":
    main()


